﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Twitterizer;


namespace Rsa
{
    class GestorTwitter
    {
        /*CONTA DO TWITTER*/
        /* USERNAME: EI_TESTE */
        /* PASSWORD: EI2101029 */

        private GestorConfigXML Gxml = null;
        private List<Lista> _listaTwitter = new List<Lista>();

        private string _url = null;
        private string _consumerkey = null;
        private string _consumersecret = null;
        private string _pin = null;
        private string _acesstoken = null;
        private string _acesstokensecret = null;
        private string _requestacesstoken = null;
        private string _requestacesstokensecret = null;
        private string _userid = null;

        private string callbackAddy = "oob";
        private TwitterResponse<TwitterStatusCollection> response;

        #region CoisasVelhas
        /*
       private string consumerKey = "1sMJ4E9E5xWu4Wt8u0LVIw";
       private string consumerSecret = "GQuHLO3jfnHE6tbRokjrGWvCLtk8kpJwre6ZinKaxo";
       private  string callbackUrl = "None";
      

       private string requestTokenUrl = "https://api.twitter.com/oauth/request_token";
       private string AuthorizeUrl = "https://api.twitter.com/oauth/authorize";
       private string AcessTokenUrl = "https://api.twitter.com/oauth/access_token";

       private string AcessToken ="935512681-9mewM9kTmzEHTxQiygseWVZ9H51LkHWnBzShTdKP";
       private string AcessTokenSecret="VTB1Ru9MzdppxWnQyLZQp3jkqEzG5Sq9XFWZqRyTxeU";
       private bool aux;

       private string url = "http://twitter.com/oauth/authorize?oauth_token=[request token]";
        */

        #endregion


        public GestorTwitter(GestorConfigXML gx)
        {

            Gxml = gx;
            this.loadConfigTwitter();
        }

        public bool loadConfigTwitter()
        {
            Hashtable hash = Gxml.loadTwitter();

            Console.WriteLine("LoadConfig Test ");

            Url = (string)hash["url"];
            if (string.IsNullOrEmpty(Url.Trim()))
                Url = null;

            ConsumerKey = (string)hash["consumerkey"];
            if (string.IsNullOrEmpty(ConsumerKey.Trim()))
                ConsumerKey = null;

            ConsumerSecret = (string)hash["consumersecret"];
            if (string.IsNullOrEmpty(ConsumerSecret.Trim()))
                ConsumerSecret = null;

            Pin = (string)hash["pin"];
            if (string.IsNullOrEmpty(Pin.Trim()))
                Pin = null;

            AcessToken = (string)hash["acesstoken"];
            if (string.IsNullOrEmpty(AcessToken.Trim()))
                AcessToken = null;

            AcessTokenSecret = (string)hash["acesstokensecret"];
            if (string.IsNullOrEmpty(AcessTokenSecret.Trim()))
                AcessTokenSecret = null;

            RequestAcessToken = (string)hash["requestacesstoken"];
            if (string.IsNullOrEmpty(RequestAcessToken.Trim()))
                RequestAcessToken = null;

            RequestAcessTokenSecret = (string)hash["requestacesstokensecret"];
            if (string.IsNullOrEmpty(RequestAcessTokenSecret.Trim()))
                RequestAcessTokenSecret = null;

            UserId = (string)hash["userid"];
            if (string.IsNullOrEmpty(UserId.Trim()))
                UserId = null;

            if (UserId != null) {
                return true;
            }
            return false;
        }


        public void Start()
        {
            Console.WriteLine(" -- START -- ");
            try
            {
                OAuthTokenResponse request = OAuthUtility.GetRequestToken(ConsumerKey, ConsumerSecret, callbackAddy);
                string url = String.Format("http://twitter.com/oauth/authorize?oauth_token={0}", request.Token);
                System.Diagnostics.Process.Start(url);

                Console.WriteLine("######## START ########");

                Console.WriteLine("Request Token :" + request.Token);
                Console.WriteLine("Reques Token Secret :" + request.TokenSecret);


                Gxml.guardaTwitterRequest(request.Token, request.TokenSecret);
            }
            catch (Exception e)
            {
                Console.WriteLine("Erro: " + e);

            }

        }

        public bool Auth(string pin)
        {



            loadConfigTwitter();

            Console.WriteLine(" -- AUTENTICACAO -- ");
            Console.WriteLine("Request Acess Token :" + RequestAcessToken);
            Console.WriteLine("Pin :" + pin);

            try
            {

                OAuthTokenResponse tokens = OAuthUtility.GetAccessToken(ConsumerKey, ConsumerSecret, RequestAcessToken, pin);


                string userAccessToken = tokens.Token;
                string userAccessSecret = tokens.TokenSecret;
                string userName = tokens.ScreenName;
                decimal userId = tokens.UserId;

                Console.WriteLine("########## AUTH #############");
                Console.WriteLine("User AcessToken :" + tokens.Token);
                Console.WriteLine("User Acess Secret :" + tokens.TokenSecret);
                Console.WriteLine("Username :" + tokens.ScreenName);
                Console.WriteLine("USER ID :" + tokens.UserId);

                Gxml.guardaTwitterId(tokens.Token.ToString(), tokens.TokenSecret.ToString(), tokens.UserId.ToString());



            }
            catch (Exception e)
            {
                Console.WriteLine("Erro: " + e);
                return false;
            }
            return true;
        }

        public void valida() {


            OAuthTokens userToken = new OAuthTokens()
            {
                ConsumerKey = ConsumerKey,
                ConsumerSecret = ConsumerSecret,
                AccessToken = AcessToken,
                AccessTokenSecret = AcessTokenSecret,
            };

            TwitterResponse<TwitterUser> twitterResponse = TwitterAccount.VerifyCredentials(userToken);

            if (twitterResponse.Result == RequestResult.Success)
            {
                Console.WriteLine("Success! Verified as {0}", twitterResponse.ResponseObject.ScreenName);

                Console.WriteLine("############ DADOS ###########");
                Console.WriteLine("Consumer Key : " + ConsumerKey);
                Console.WriteLine("Consumer Secret : " + ConsumerSecret);
                Console.WriteLine("User Acess Token : " + AcessToken);
                Console.WriteLine("User Acess Token Secret : " + AcessTokenSecret);


                TwitterResponse<TwitterStatusCollection> response;

                try
                {
                    response = TwitterTimeline.HomeTimeline(userToken);
                }
                catch (TwitterizerException ex)
                {
                    throw;
                }

                if (response.Result == RequestResult.Success)
                {
                    Console.WriteLine("PODES VER O HOMETIMELINE" + response.ErrorMessage);
                }
                else
                {
                    HandleTwitterizerError<TwitterStatusCollection>(response);
                }
            }
        
        }

        public bool Dados(int opcao)
        {
            if (opcao == 0)
            {
                //opcao 1

            }
            else if (opcao == 1)
            {
                //opcao 2

            }
            else if (opcao == 2)
            {
                //opcao 3
            }

            ListaTwitter = new List<Lista>();

            if (loadConfigTwitter() != false)
            {

                OAuthTokens userToken = new OAuthTokens()
                {
                    ConsumerKey = ConsumerKey,
                    ConsumerSecret = ConsumerSecret,
                    AccessToken = AcessToken,
                    AccessTokenSecret = AcessTokenSecret,
                };


                TwitterResponse<TwitterUser> twitterResponse = TwitterAccount.VerifyCredentials(userToken);

                if (twitterResponse.Result == RequestResult.Success)
                {
                    Console.WriteLine("Success! Verified as {0}", twitterResponse.ResponseObject.ScreenName);

                    Console.WriteLine("############ DADOS ###########");
                    Console.WriteLine("Consumer Key : " + ConsumerKey);
                    Console.WriteLine("Consumer Secret : " + ConsumerSecret);
                    Console.WriteLine("User Acess Token : " + AcessToken);
                    Console.WriteLine("User Acess Token Secret : " + AcessTokenSecret);


                    TwitterResponse<TwitterStatusCollection> response;

                    try
                    {
                        response = TwitterTimeline.HomeTimeline(userToken);
                    }
                    catch (TwitterizerException ex)
                    {
                        throw;
                    }

                    if (response.Result == RequestResult.Success)
                    {
                        Console.WriteLine("TENHO DADOS");
                    }
                    else
                    {
                        Console.WriteLine("NAO TENHO DADOS");
                        HandleTwitterizerError<TwitterStatusCollection>(response);
                    }


                    foreach (var userElement in response.ResponseObject)
                    {

                        Lista ls = new Lista();

                        Console.WriteLine("AUTOR " + userElement.User.Name);
                        ls.Titulo = userElement.User.Name;
                        Console.WriteLine("TEXT " + userElement.Text);
                        ls.Resumo = userElement.Text.ToString();
                        ls.Data = userElement.CreatedDate;
                        ls.Imagem = userElement.User.ProfileImageLocation;
                        ls.Corpo = "<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'>";
                        ls.Corpo += userElement.LinkifiedText();
                        ListaTwitter.Add(ls);
                    }



                }
                else
                {

                    Console.WriteLine("Failed! \"{0}\"", twitterResponse.ErrorMessage ?? "Not Authorized.");

                }

                return true;

             
            }
            else {
                Console.WriteLine("NAO TENHO DADOS");
                return false;
            }
        }

        public static void HandleTwitterizerError<T>(TwitterResponse<T> response) where T : Twitterizer.Core.ITwitterObject
        {
            // Something bad happened, time to figure it out.
            string rawDataReturnedByTwitter = response.Content;
            string errorMessageReturnedByTwitter = response.ErrorMessage;

            // The possible reasons something went wrong
            switch (response.Result)
            {
                case RequestResult.FileNotFound:
                    break;
                case RequestResult.BadRequest:
                    break;
                case RequestResult.Unauthorized:
                    break;
                case RequestResult.NotAcceptable:
                    break;
                case RequestResult.RateLimited:
                    break;
                case RequestResult.TwitterIsDown:
                    break;
                case RequestResult.TwitterIsOverloaded:
                    break;
                case RequestResult.ConnectionFailure:
                    break;
                case RequestResult.Unknown:
                    break;
                default:
                    break;
            }
        }

        public bool Post(String text)
        {

            /* POST A FUNCIONAR, RETORNA TRUE OU FALSE CONSUANTE FAZ O POST */
            /* TEM TRY CATCH PARA OS ERROS */

            bool result = false;

            try
            {

                OAuthTokens userToken = new OAuthTokens()
                {

                    ConsumerKey = ConsumerKey,
                    ConsumerSecret = ConsumerSecret,
                    AccessToken = AcessToken,
                    AccessTokenSecret = AcessTokenSecret,


                };

                TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(userToken, text);
                if (tweetResponse.Result == RequestResult.Success)
                {
                    Console.WriteLine("Success");
                    result = true;
                }
                else
                {
                    Console.WriteLine("Error");
                    result = false;
                }
            }
            catch (Exception e)
            {

                Console.WriteLine("ERRO : " + e);
                result = false;

            }

            return result;
        }

        #region set and gets

        public string Url
        {
            get { return _url; }
            set { _url = value; }
        }

        public string ConsumerKey
        {
            get { return _consumerkey; }
            set { _consumerkey = value; }
        }

        public string ConsumerSecret
        {
            get { return _consumersecret; }
            set { _consumersecret = value; }
        }

        public string Pin
        {
            get { return _pin; }
            set { _pin = value; }
        }

        public string AcessToken
        {
            get { return _acesstoken; }
            set { _acesstoken = value; }
        }

        public string AcessTokenSecret
        {

            get { return _acesstokensecret; }
            set { _acesstokensecret = value; }
        }

        public string RequestAcessToken
        {

            get { return _requestacesstoken; }
            set { _requestacesstoken = value; }
        }

        public string RequestAcessTokenSecret
        {

            get { return _requestacesstokensecret; }
            set { _requestacesstokensecret = value; }
        }

        public string UserId
        {

            get { return _userid; }
            set { _userid = value; }
        }

        #endregion

        public List<Lista> ListaTwitter
        {
            get { return _listaTwitter; }
            set { _listaTwitter = value; }
        }

    }

}
